package com.zdkj.subway.check.controller.subwayRat.conductorDifferences.SwAuConductorShort;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zdkj.common.core.util.R;
import com.zdkj.common.data.cache.RedisTemplateConfig;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.controller.CommonController;
import com.zdkj.subway.check.entity.*;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.*;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.service.SwCkElectronicReceiptService;
import com.zdkj.subway.check.service.impl.subwayRat.conductorDifferences.SwAuConductorShort.SwAuConductorShortServiceImpl;
import com.zdkj.subway.check.util.DateFormat;
import com.zdkj.subway.check.util.ExcelCellUtil;
import com.zdkj.subway.check.util.LineOrStation;
import com.zdkj.subway.check.util.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 报表差错信息
 */
@RestController
@RequestMapping("/check")
@Slf4j
@Api(value = "check", tags = "营销车票审核")
public class SwAuConductorShortController {

    @Autowired
    private SwAuConductorShortServiceImpl swAuConductorShortService;
    @Autowired
    private SwAuConductorShortMapper swAuConductorShortMapper;
    @Autowired
    private SwAuMarketingTicketMapper swAuMarketingTicketMapper;
    @Autowired
    private SwStMarketingTicketMapper swStMarketingTicketMapper;
    @Autowired
    private SwStTicketInformationCheckMapper swStTicketInformationCheckMapper;
    @Autowired
    private CommonController commonController;
    @Autowired
    private SwParamStationMapper swParamStationMapper;
    @Autowired
    private SwParamLineMapper swParamLineMapper;
    @Autowired
    private SwCkElectronicReceiptService swCkElectronicReceiptService;
    @Resource
    RedisTemplateConfig redisTemplateConfig;
    @Resource
    SwAuCenterConductorAmountDifferenceMapper swAuCenterConductorAmountDifferenceMapper;

    /**
     * 票卡信息查询列表
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/getSwAuConductorShortLimit")
    @ApiOperation(value = "票卡信息查询列表", notes = "票卡信息查询列表")
    public Page getSwAuConductorShortLimit(Page page,@RequestParam Map<String,String> param){
        Map req = new HashMap();
        List<Integer> ids = new ArrayList<>();
        if(null != param.get("ids")){
            ids = (List)JSONObject.parseArray(String.valueOf(param.get("ids")));
        }else{
            return page;
        }
        List swAuConductorShortList = new ArrayList();
        for(Integer id : ids){
            req.put("id",id);
            //根据id查询
            List<Map<String, Object>> swAuConductorShort = swAuConductorShortMapper.getSwAuConductorShort(req);
            swAuConductorShortList.addAll(swAuConductorShort);
        }
        page.setData(swAuConductorShortList,true);
        return page;
    }

    /**
     * 营销车票和库存对比查询
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/getSwAuMarketingTicket")
    @ApiOperation(value = "营销车票和库存对比查询", notes = "营销车票和库存对比查询")
    public Page getSwAuMarketingTicket(Page page,@RequestParam Map<String,String> param){
        List<Map<String, Object>> swAuMarketingTicket = swAuMarketingTicketMapper.getSwAuMarketingTicket(param);
        page.setData(swAuMarketingTicket,true);
        return page;
    }

    /**
     * 修改营销车票审核数据
     * @param
     * @return
     */
    @PutMapping("/updateSwAuMarketingTicket")
    @ApiOperation(value = "修改营销车票审核数据", notes = "修改营销车票审核数据")
    public Result updateSwAuMarketingTicket(@RequestParam Map<String,String> param){
        String ids = param.get("ids");
        List<Integer> asList = (List<Integer>) JSON.parse(ids);
        String remark = param.get("remark");
        PigxUser user = SecurityUtils.getUser();
        LambdaUpdateWrapper<SwAuMarketingTicket> updateWrapper =
                Wrappers.<SwAuMarketingTicket>lambdaUpdate().set(SwAuMarketingTicket::getConfirmStatus, "1")
                .set(SwAuMarketingTicket::getConfirmTime, new Date())
                .set(SwAuMarketingTicket::getCreatorName, user.getNikeName())
                .set(SwAuMarketingTicket::getRemark, remark)
                .set(SwAuMarketingTicket::getCreatorId, user.getId()).in(SwAuMarketingTicket::getId, asList);
        swAuMarketingTicketMapper.update(null,updateWrapper);
        //for(Integer id : ids){
        //    SwAuMarketingTicket swAuMarketingTicket = new SwAuMarketingTicket();
        //    swAuMarketingTicket.setId(Long.valueOf(id));
        //    //确认状态
        //    swAuMarketingTicket.setConfirmStatus("1");
        //    swAuMarketingTicket.setConfirmTime(new Date());
        //    swAuMarketingTicket.setCreatorName(user.getNikeName());
        //    swAuMarketingTicket.setCreatorId(user.getId());
        //    swAuMarketingTicketMapper.updateById(swAuMarketingTicket);
        //}
        Result res=new Result(ResultDetailMsg.OK);
        return res;
    }

    /**
     * 获取售票员补款
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/getSwAuConductorShort")
    @ApiOperation(value = "获取售票员补款", notes = "获取售票员补款")
    public Page getSwAuConductorShort(Page page,@RequestParam Map<String,String> param){
        List<Map<String, Object>> swAuConductorShort = swAuConductorShortService.getSwAuConductorShort(param);
        page.setData(swAuConductorShort,true);
        return page;
    }

    /**
     * 售票员补款设置入账日期 和 补款期限
     * @param param
     * @return
     * @throws Exception
     */
    @RequestMapping("/updateSwAuConductorShortLimit")
    @ApiOperation(value = "售票员补款设置入账日期 和 补款期限", notes = "售票员补款设置入账日期 和 补款期限")
    public Result updateSwAuConductorShortLimit(@RequestParam Map<String,String> param) throws Exception {
        if(null != param.get("list")){
            JSONArray list = JSONObject.parseArray(param.get("list"));
            if(null != list){
                List<SwAuConductorShort> swAuConductorShorts = JSONObject.parseArray(list.toJSONString(), SwAuConductorShort.class);
                for(SwAuConductorShort swAuConductorShort :swAuConductorShorts){
                    if(ObjectUtil.isNotEmpty(swAuConductorShort.getAccountTime())){
                        // accountTime  年-月-日  supPaymentTime  年月日小时分秒
                        // if accountTime不等于空  把 accountTime更新到supPaymentTime里的年月日里 小时分秒保留
                        Date accountTime = swAuConductorShort.getAccountTime();
                        String accountTimeStr = DateFormat.date_ex_str(accountTime, "yyyy-MM-dd HH:mm:ss");
                        String accountDateStr = accountTimeStr.substring(0, 10);

                        Date supPaymentTime = swAuConductorShort.getSupPaymentTime();
                        String supPaymentTimeStr = DateFormat.date_ex_str(supPaymentTime, "yyyy-MM-dd HH:mm:ss");
                        String supPaymentDateStr = supPaymentTimeStr.substring(supPaymentTimeStr.length()-9);

                        //拼接
                        String newDateTime = accountDateStr+supPaymentDateStr;
                        swAuConductorShort.setSupPaymentTime(DateFormat.stringToDateFormat(newDateTime));
                    }

                    swAuConductorShortMapper.updateById(swAuConductorShort);
                }
            }
        }
        Result res=new Result(ResultDetailMsg.OK);
        return res;
    }

    /**
     * 售票员补款信息下发通知
     * @param param
     * @return
     */
    @RequestMapping("/updateSwAuConductorShort")
    @ApiOperation(value = "售票员补款信息下发通知", notes = "售票员补款信息下发通知")
    @Transactional(rollbackFor = Exception.class)
    public Result updateSwAuConductorShort(@RequestBody Map<String,Object> param){
        PigxUser user = SecurityUtils.getUser();
        try{
            if(null != param.get("list")){
                List<Map<String,Object>> list = (List)JSONObject.parseArray(String.valueOf(param.get("list")));
                for(Map<String,Object> m : list){
                    String id = String.valueOf(m.get("id"));
                    String supPaymentLimit = String.valueOf(m.get("supPaymentLimit"));
                    Calendar calendar = new GregorianCalendar();
                    calendar.setTime(new Date());
                    calendar.add(calendar.DATE,Integer.valueOf(supPaymentLimit));
                    SwAuConductorShort swAuConductorShort = swAuConductorShortMapper.selectById(Long.valueOf(id));
                    if(ObjectUtil.isNotEmpty(swAuConductorShort)){
                        swAuConductorShort.setIsNotice(1);
                        swAuConductorShort.setNoticeTime(new Date());
                        swAuConductorShort.setNoticeName(user.getNikeName());
                        swAuConductorShort.setSupPaymentTimelimit(calendar.getTime());
                        swAuConductorShortMapper.updateById(swAuConductorShort);
                        Integer diffId = swAuConductorShort.getDiffId();
                        SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference = new SwAuCenterConductorAmountDifference();
                        swAuCenterConductorAmountDifference.setId(diffId);
                        swAuCenterConductorAmountDifference.setSuppState("1");//0；未加入补款 1；未补款 3；已补款
                        swAuCenterConductorAmountDifferenceMapper.updateById(swAuCenterConductorAmountDifference);
                    }
                }
                commonController.innerBatch(param);
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        Result res=new Result(ResultDetailMsg.OK);
        return res;
    }

    /**
     * 营销车票转账及团购数据审核查询
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/getSwStMarketingTicket")
    @ApiOperation(value = "营销车票转账及团购数据审核查询", notes = "营销车票转账及团购数据审核查询")
    public R getSwStMarketingTicket(com.baomidou.mybatisplus.extension.plugins.pagination.Page page,@RequestParam Map<String,Object> param){
        PigxUser user = SecurityUtils.getUser();
        if(user.getBelongToLine()){
            List lineList = LineOrStation.getmanagementLine();
            param.put("lines",lineList);
        }else{
            List lineList = LineOrStation.getLineOrManagementLine();
            param.put("lines",lineList);
        }
        IPage<SwStMarketingTicket> swStMarketingTicket = swAuConductorShortService.getSwStMarketingTicket(page,param);
        return R.ok(swStMarketingTicket);
    }

    /**
     * 批量审核数据
     * @param ids
     * @return
     */
    @RequestMapping("/batchAduitSwStMarketingTicket")
    @ApiOperation(value = "批量审核数据", notes = "批量审核数据")
    public Result batchAduitSwStMarketingTicket(String ids,String auditStatus){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            SwStMarketingTicket swStMarketingTicket=new SwStMarketingTicket();
            QueryWrapper<SwStMarketingTicket> queryWrapper=new QueryWrapper<>();
            queryWrapper.in("id",ids.split(","));
            swStMarketingTicket.setAuditStatus(auditStatus);
            swStMarketingTicket.setAuditPersonid(UserInfo.getId());
            swStMarketingTicket.setAuditPersoncode(UserInfo.getUserCode());
            swStMarketingTicket.setAuditTime(new Date());
            int update = swStMarketingTicketMapper.update(swStMarketingTicket, queryWrapper);
        }catch (Exception e){
            res.setMsg("操作失败");
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
        }
        return res;
    }

    /**
     * 营销车票数据审核点击生成电子回执单“对账数据”
     * @param startDate   开始日期：yyyy-MM-dd
     * @param endDate     结束日期：yyyy-MM-dd
     * @return
     */
    @ApiOperation(value = "营销车票数据审核点击生成电子回执单“对账数据”", notes = "营销车票数据审核点击生成电子回执单“对账数据”")
    @GetMapping("/getElectronicReceipt")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "开始日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "endDate", value = "结束日期：yyyy-MM-dd", dataTypeClass = String.class)
            }
    )
    public R getElectronicReceipt(String startDate, String endDate) throws SQLException {

        boolean isDateCondition = StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate);
        if (isDateCondition) {
            LocalDate startDateLocalDate = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDate endDateLocalDate = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            List<Map<String, Object>> mapList = swStMarketingTicketMapper.getElectronicReceipt(startDateLocalDate, endDateLocalDate);

            ArrayList<SwCkElectronicReceipt> arrayList = new ArrayList<>();

            PigxUser user = SecurityUtils.getUser();
            for (Map<String, Object> map : mapList) {

                SwCkElectronicReceipt swCkElectronicReceipt = new SwCkElectronicReceipt();

                QueryWrapper<SwCkElectronicReceipt> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(SwCkElectronicReceipt::getLineCode,map.get("LINE_CODE").toString());
                wrapper.lambda().eq(SwCkElectronicReceipt::getStationCode,map.get("STATION_CODE").toString());
                wrapper.lambda().eq(SwCkElectronicReceipt::getTicketType,map.get("TICKET_TYPE").toString());
                wrapper.lambda().eq(SwCkElectronicReceipt::getBookkeepingTime,map.get("BOOKKEEPING_TIME"));
                SwCkElectronicReceipt one = swCkElectronicReceiptService.getOne(wrapper);
                //boolean isJump = true;
                if(one!=null){
//                    if("1".equals(one.getConfirmStatus())){
//                        isJump = false;
//                    }
                    if(StringUtils.isEmpty(one.getReturnNumber()) || map.get("RETURN_NUMBER").toString().equals(one.getReturnNumber())){
                        if("1".equals(one.getReturnOrderType())){
                            swCkElectronicReceipt.setId(one.getId());
                            swCkElectronicReceipt.setConfirmStatus("0");
                        }
                        if("2".equals(one.getReturnOrderType())){
                            swCkElectronicReceipt.setId(one.getId());
                            swCkElectronicReceipt.setConfirmStatus("0");
                        }
                    }
                }

//               if(isJump){
//
//               }
                swCkElectronicReceipt.setLineCode(map.get("LINE_CODE").toString());
                swCkElectronicReceipt.setStationCode(map.get("STATION_CODE").toString());
                swCkElectronicReceipt.setTicketType(map.get("TICKET_TYPE").toString());
                swCkElectronicReceipt.setTicketName(map.get("TICKET_NAME").toString());
                swCkElectronicReceipt.setSaleNumber((Integer) map.get("SALE_NUMBER"));
                swCkElectronicReceipt.setUnitTicketPrice((BigDecimal) map.get("UNIT_TICKET_PRICE"));
                swCkElectronicReceipt.setSaleAmount((BigDecimal) map.get("SALE_AMOUNT"));
                swCkElectronicReceipt.setBankElecOrderAmount((BigDecimal) map.get("BANK_ELEC_ORDER_AMOUNT"));
                swCkElectronicReceipt.setDiffElecAmount((BigDecimal) map.get("DIFF_ELEC_AMOUNT"));
                String bookkeepingTime = String.valueOf(map.get("BOOKKEEPING_TIME"));
                swCkElectronicReceipt.setBookkeepingTime(DateFormat.StringTurnLocalDate(bookkeepingTime));
                if(ObjectUtil.isEmpty(map.get("RETURN_NUMBER"))){
                    return R.failed("日期范围内的营销车票未找到回执单号/单据号！");
                }
                swCkElectronicReceipt.setReturnNumber(String.valueOf(map.get("RETURN_NUMBER")));
                swCkElectronicReceipt.setReturnOrderType(map.get("RETURN_ORDER_TYPE").toString());
                swCkElectronicReceipt.setDataType(map.get("DATA_TYPE").toString());
                swCkElectronicReceipt.setConfirmStatus(map.get("CONFIRM_STATUS").toString());
                swCkElectronicReceipt.setPaymentType(map.get("PAYMENT_TYPE").toString());
                swCkElectronicReceipt.setDiscountAmount((BigDecimal) map.get("DISCOUNT_AMOUNT"));
                swCkElectronicReceipt.setCreatorId(user.getId());
                swCkElectronicReceipt.setCreatorName(user.getNikeName());
                arrayList.add(swCkElectronicReceipt);
            };
            if(arrayList.size()>0){
                boolean isOk = swCkElectronicReceiptService.saveOrUpdateBatch(arrayList);
                if(isOk){
                    swStMarketingTicketMapper.updateExecuteStatus(startDateLocalDate, endDateLocalDate);
                }
                return R.ok("生成成功！");
            }else {
                return R.failed("没有可生成的数据！");
            }
        }
        return R.ok();
    }

    /**
     * 线下正常售卖售票员
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/getSwStMarketingTicketOffineSell")
    @ApiOperation(value = "线下正常售卖售票员", notes = "线下正常售卖售票员")
    public Page getSwStMarketingTicketOffineSell(Page page,@RequestParam Map<String,String> param){
        List<Map<String, Object>> swStMarketingTicketOffineSell = swAuConductorShortService.getSwStMarketingTicketOffineSell(param);
        page.setData(swStMarketingTicketOffineSell);
        return page;
    }

    /**
     * 营销车票团购售卖
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/getSwStMarketingTicketGroupSell")
    @ApiOperation(value = "营销车票团购售卖", notes = "营销车票团购售卖")
    public Page getSwStMarketingTicketGroupSell(Page page,@RequestParam Map<String,String> param){
        List<Map<String, Object>> swStMarketingTicketGroupSell = swAuConductorShortService.getSwStMarketingTicketGroupSell(param);
        page.setData(swStMarketingTicketGroupSell);
        return page;
    }

    /**
     * 营收车票线下取票明细表
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/getSwStMarketingTicketOffineTakeTicket")
    @ApiOperation(value = "营收车票线下取票明细表", notes = "营收车票线下取票明细表")
    public Page getSwStMarketingTicketOffineTakeTicket(Page page,@RequestParam Map<String,String> param){
        List<Map<String, Object>> swStMarketingTicketGroupSell = swAuConductorShortService.getSwStMarketingTicketOffineTakeTicket(param);
        page.setData(swStMarketingTicketGroupSell);
        return page;
    }

    /**
     * 回馈车站提交票卡信息
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/getSwStTicketInformationCheck")
    @ApiOperation(value = "回馈车站提交票卡信息", notes = "回馈车站提交票卡信息")
    public Page getSwStTicketInformationCheck(Page page,@RequestParam Map<String,String> param){
        List<Map<String, Object>> swStTicketInformationCheck = swStTicketInformationCheckMapper.getSwStTicketInformationCheck(param);
        page.setData(swStTicketInformationCheck);
        return page;
    }

    /**
     * 回馈车站提交票卡信息清分
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/getSwStTicketInformationCheckToQF")
    @ApiOperation(value = "回馈车站提交票卡信息清分", notes = "回馈车站提交票卡信息清分")
    public Page getSwStTicketInformationCheckToQF(Page page,@RequestParam Map<String,String> param){
        List<Map<String, Object>> swStTicketInformationCheck = swStTicketInformationCheckMapper.getSwStTicketInformationCheck(param);
        page.setData(swStTicketInformationCheck,true);
        return page;
    }

    /**
     * 编辑回馈车站提交票卡信息
     * @param param
     * @return
     */
    @RequestMapping("/updateSwStTicketInformationCheck")
    @ApiOperation(value = "编辑回馈车站提交票卡信息", notes = "编辑回馈车站提交票卡信息")
    public Result updateSwStTicketInformationCheck(@RequestParam Map<String,String> param){
        if(null != param.get("ids")){
            List<Integer> ids = (List)JSONObject.parseArray(String.valueOf(param.get("ids")));
            for(Integer id : ids){
                SwStTicketInformationCheck swStTicketInformationCheck = swStTicketInformationCheckMapper.selectById(id);
                swStTicketInformationCheck.setAccDataStatus(1);
                String lineDataStatus = param.get("lineDataStatus");
                String accDataStatus = param.get("accDataStatus");
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(accDataStatus)){
                    swStTicketInformationCheck.setAccDataStatus(Integer.parseInt(accDataStatus));
                }
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(lineDataStatus)){
                    swStTicketInformationCheck.setLineDataStatus(Integer.parseInt(lineDataStatus));
                }
                swStTicketInformationCheck.setDiffAmount(swStTicketInformationCheck.getAmount().subtract(swStTicketInformationCheck.getReplyAmount()));
                swStTicketInformationCheckMapper.updateById(swStTicketInformationCheck);
            }
        }
        Result res=new Result(ResultDetailMsg.OK);
        return res;
    }

    /**
     * 编辑回馈车站提交票卡信息清分
     * @param param
     * @return
     * @throws Exception
     */
    @RequestMapping("/updateSwStTicketInformationCheckToQF")
    @ApiOperation(value = "编辑回馈车站提交票卡信息清分", notes = "编辑回馈车站提交票卡信息清分")
    public Result updateSwStTicketInformationCheckToQF(@RequestParam Map<String,Object> param)throws Exception{
        if(null != param.get("id")){
            SwStTicketInformationCheck swStTicketInformationCheck = new SwStTicketInformationCheck();
            SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");
            swStTicketInformationCheck.setId(Long.valueOf(param.get("id").toString()));
            swStTicketInformationCheck.setInTime(dff.parse(param.get("inTime").toString()));
            swStTicketInformationCheck.setOutTime(dff.parse(param.get("outTime").toString()));
            Map<String,Object> req=new HashMap<>();
            req.put("line_code",param.get("inLineCode"));
            req.put("code",param.get("inStationCode"));
            List<SwParamStation> swParamStations= swParamStationMapper.selectByMap(req);
            if(null != swParamStations && 0 != swParamStations.size())
                swStTicketInformationCheck.setInStationName(swParamStations.get(0).getName());
            req.put("line_code",param.get("outLineCode"));
            req.put("code",param.get("outStationCode"));
            swParamStations= swParamStationMapper.selectByMap(req);
            if(null != swParamStations && 0 != swParamStations.size())
                swStTicketInformationCheck.setOutStationName(swParamStations.get(0).getName());
            req.clear();
            req.put("code",param.get("inLineCode"));
            List<SwParamLine> swParamLines = swParamLineMapper.selectByMap(req);
            if(null != swParamLines && 0 != swParamLines.size())
                swStTicketInformationCheck.setInLineName(swParamLines.get(0).getName());
            req.put("code",param.get("outLineCode"));
            swParamLines = swParamLineMapper.selectByMap(req);
            if(null != swParamLines && 0 != swParamLines.size())
                swStTicketInformationCheck.setOutLineName(swParamLines.get(0).getName());
            swStTicketInformationCheck.setInLineCode(param.get("inLineCode").toString());
            swStTicketInformationCheck.setInStationCode(param.get("inStationCode").toString());
            swStTicketInformationCheck.setOutLineCode(param.get("outLineCode").toString());
            swStTicketInformationCheck.setOutStationCode(param.get("outStationCode").toString());
            swStTicketInformationCheck.setReplyAmount(BigDecimal.valueOf(Integer.valueOf(param.get("replyAmount").toString())));
            swStTicketInformationCheckMapper.updateById(swStTicketInformationCheck);
        }
        Result res=new Result(ResultDetailMsg.OK);
        return res;
    }

    /**
     * 票卡文件导入
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/uploadTicketFileQF")
    @ApiOperation(value = "票卡文件导入", notes = "票卡文件导入")
    public Result uploadTicketFileQF(@RequestParam MultipartFile file, HttpServletRequest request){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            String fileName = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            Workbook wb=null;
            //根据文件后缀（xls/xlsx）进行判断
            if (fileName.endsWith("xls")){
//                FileInputStream fis = new FileInputStream(f);   //文件流对象
                wb = new HSSFWorkbook(inputStream);
            }else if (fileName.endsWith("xlsx")){
                wb = new XSSFWorkbook(inputStream);
            }else {
                result.setMsg("请使用xls、xlsx格式文件");
                result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
                return result;
            }
            List<Map<String,Object>> list=new ArrayList<>();
            Sheet sheetAt = wb.getSheetAt(0);
            String static_date="";
            for(int i=0;i<=sheetAt.getLastRowNum();i++){
                Map<String,Object> one=new HashMap<>();
                Row row = sheetAt.getRow(i);
                if(i<1){
                    continue;
                }
                //主键	提交线路	提交站点	卡号	车站提交金额/次数	ACC回馈金额/次数	差异	进站线路	进站名称	进站时间	出站线路	出站名称	出站时间	录入人	录入人工号	录入时间	状态

                String id = ExcelCellUtil.getCellContent(row.getCell(0));
                String sublineName = ExcelCellUtil.getCellContent(row.getCell(1));
                String substationName = ExcelCellUtil.getCellContent(row.getCell(2));
                String card = ExcelCellUtil.getCellContent(row.getCell(3));
                String subAmountCount = ExcelCellUtil.getCellContent(row.getCell(4));
                String accAmountCount = ExcelCellUtil.getCellContent(row.getCell(5));
                String chayi = ExcelCellUtil.getCellContent(row.getCell(6));
                String centerlineName = ExcelCellUtil.getCellContent(row.getCell(7));
                String centerstationName = ExcelCellUtil.getCellContent(row.getCell(8));
                String centerTime = ExcelCellUtil.getCellContent(row.getCell(9));
                String outlineName = ExcelCellUtil.getCellContent(row.getCell(10));
                String outstationName = ExcelCellUtil.getCellContent(row.getCell(11));
                String outTime = ExcelCellUtil.getCellContent(row.getCell(12));
                String inputPerson = ExcelCellUtil.getCellContent(row.getCell(13));
                String inputPersonCode = ExcelCellUtil.getCellContent(row.getCell(14));
                String inputTime = ExcelCellUtil.getCellContent(row.getCell(15));
                String status = ExcelCellUtil.getCellContent(row.getCell(16));

                one.put("sublineName",sublineName);
                one.put("substationName",substationName);
                one.put("card",card);
                one.put("subAmountCount",subAmountCount);
                one.put("accAmountCount",accAmountCount);
                one.put("chayi",chayi);
                one.put("centerlineName",centerlineName);
                one.put("centerstationName",centerstationName);
                one.put("centerTime",centerTime);
                one.put("outlineName",outlineName);
                one.put("outstationName",outstationName);
                one.put("outTime",outTime);
                one.put("inputPerson",inputPerson);
                one.put("inputPersonCode",inputPersonCode);
                one.put("inputTime",inputTime);
                one.put("status",status);
                list.add(one);
            }
            JSONObject res=new JSONObject();
            res.put("list",list);
            redisTemplateConfig.redisTemplate().opsForValue().set(UserInfo.getUserCode()+"_ticket"+"_export",res.toJSONString());
            result.setData(list);
        }catch (Exception e){
            e.printStackTrace();
            log.error("文件上传处理失败{}",e);
            result.setMsg("文件上传处理失败");
            result.setResult(ResultDetailMsg.MONDIFY_FILE_FAILD);
        }
        return result;
    }

    /**
     * 票卡文件导入清分
     * @param request
     * @return
     */
    @RequestMapping("/importTicketFileQF")
    @ApiOperation(value = "票卡文件导入清分", notes = "票卡文件导入清分")
    public Result importTicketFileQF(HttpServletRequest request){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            String _export = (String) redisTemplateConfig.redisTemplate().opsForValue().get(UserInfo.getUserCode()+"_ticket"+"_export");
            JSONObject list = JSONObject.parseObject(_export);
            JSONArray jsonArray = list.getJSONArray("list");
            for(int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String sublineName = jsonObject.getString("sublineName");
                String substationName = jsonObject.getString("substationName");
                JSONObject sub = getlinenameOrStationName(sublineName, substationName);
                String card = jsonObject.getString("card");
               String subAmountCount = jsonObject.getString("subAmountCount");
               String accAmountCount = jsonObject.getString("accAmountCount");
               String chayi = jsonObject.getString("chayi");
               String centerlineName = jsonObject.getString("centerlineName");
               String centerstationName = jsonObject.getString("centerstationName");
                JSONObject center = getlinenameOrStationName(centerlineName, centerstationName);
               String centerTime = jsonObject.getString("centerTime");
               String outlineName = jsonObject.getString("outlineName");
               String outstationName = jsonObject.getString("outstationName");
                JSONObject out = getlinenameOrStationName(outlineName, outstationName);
               String outTime = jsonObject.getString("outTime");
               String inputPerson = jsonObject.getString("inputPerson");
               String inputPersonCode = jsonObject.getString("inputPersonCode");
               String inputTime = jsonObject.getString("inputTime");
               String status = jsonObject.getString("status");

                SwStTicketInformationCheck swStTicketInformationCheck=new SwStTicketInformationCheck();

                swStTicketInformationCheck.setSubmitLineCode(sub.getString("lineCode"));
                swStTicketInformationCheck.setSubmitStationCode(sub.getString("stationCode"));
                swStTicketInformationCheck.setCardOrder(card);
                swStTicketInformationCheck.setInputPersonCode(inputPersonCode);
                QueryWrapper<SwStTicketInformationCheck> queryWrapper=new QueryWrapper<SwStTicketInformationCheck>();
                queryWrapper.setEntity(swStTicketInformationCheck);
                List<SwStTicketInformationCheck> swStTicketInformationChecks = swStTicketInformationCheckMapper.selectList(queryWrapper);
                if(swStTicketInformationChecks.size()>0){
                    swStTicketInformationCheck=swStTicketInformationChecks.get(0);
                }

                swStTicketInformationCheck.setSubmitLineName(sublineName);
                swStTicketInformationCheck.setSubmitStationName(substationName);
                swStTicketInformationCheck.setAmount(new BigDecimal(subAmountCount));
                swStTicketInformationCheck.setReplyAmount(new BigDecimal(accAmountCount));
                swStTicketInformationCheck.setDiffAmount(new BigDecimal(chayi));
                swStTicketInformationCheck.setInLineCode(center.getString("lineCode"));
                swStTicketInformationCheck.setInLineName(centerlineName);
                swStTicketInformationCheck.setInStationCode(center.getString("stationCode"));
                swStTicketInformationCheck.setInStationName(centerstationName);
                swStTicketInformationCheck.setInTime(DateFormat.panDuanDate(centerTime));
                swStTicketInformationCheck.setOutLineCode(out.getString("lineCode"));
                swStTicketInformationCheck.setOutLineName(outlineName);
                swStTicketInformationCheck.setOutStationCode(out.getString("stationCode"));
                swStTicketInformationCheck.setOutStationName(outstationName);
                swStTicketInformationCheck.setOutTime(DateFormat.panDuanDate(outTime));
                swStTicketInformationCheck.setInputPerson(inputPerson);

                swStTicketInformationCheck.setInputTime(DateFormat.panDuanDate(inputTime));
                swStTicketInformationCheck.setAccDataStatus(1);
                swStTicketInformationCheck.setCreatorId(UserInfo.getId());
                swStTicketInformationCheck.setCreateTime(new Date());
                swStTicketInformationCheck.setCreatorName(UserInfo.getName());
                swStTicketInformationCheck.setDelFlag("0");
                swStTicketInformationCheck.setDeptId(UserInfo.getDeptId());
                swStTicketInformationCheck.setIsAddReportError("0");
                if(swStTicketInformationChecks.size()>0){
                    swStTicketInformationCheck.setRelationid(0);
                    swStTicketInformationCheckMapper.updateById(swStTicketInformationCheck);
                }else{
                    swStTicketInformationCheckMapper.insert(swStTicketInformationCheck);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            log.error("文件上传处理失败{}",e);
            result.setMsg("文件上传处理失败");
            result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
        }
        return result;
    }

    /**
     * 线路站点名称转换
     * @param lineName
     * @param stationName
     * @return
     */
    private JSONObject getlinenameOrStationName(String lineName,String stationName){
        QueryWrapper<SwParamLine> queryWrapperLine=new QueryWrapper<>();
        queryWrapperLine.eq("name",lineName);
        List<SwParamLine> swParamLines = swParamLineMapper.selectList(queryWrapperLine);
        String lineCode="";
        String stationCode="";
        if(swParamLines!=null && swParamLines.size()>0){
            lineCode=swParamLines.get(0).getCode();

            QueryWrapper<SwParamStation> queryWrapperStation=new QueryWrapper<>();
            queryWrapperStation.eq("name",stationName);
            queryWrapperStation.eq("line_code",lineCode);
            List<SwParamStation> swParamStations = swParamStationMapper.selectList(queryWrapperStation);
            if(swParamStations!=null && swParamStations.size()>0){
                stationCode=swParamStations.get(0).getCode();
            }
        }
        JSONObject res=new JSONObject();
        res.put("lineCode",lineCode);
        res.put("stationCode",stationCode);
        return res;
    }

}
